let { User, newcreate, score } = require('../models');
const auth = require('../untils/auth');
const dateTime = require('../dateTime');


let adminHome_fn = async (ctx, next) => {
    ctx.body = { code: 200, msg: '去往了管理员首页' };
};
let goAdminHome_fn = async (ctx, next) => {
    ctx.render('adminHome.html')
};


let adminCreate_fn = async (ctx, next) => {
    ctx.body = { code: 200, msg: '去往了发布问卷' };
};
let goadminCreate_fn = async (ctx, next) => {
    ctx.render('adminCreate.html')
};

let adminQsResult_fn = async (ctx, next) => {
    ctx.body = { code: 200, msg: '去往了问卷结果' };
};
/* let goAdminQsResult_fn = async (ctx, next) => {
    ctx.render('adminQsResult.html')
};
 */
let goAdminCreateSuccess_fn = async (ctx, next) => {
    ctx.render('adminCreateSuccess.html')
};


let adminUserControl_fn = async (ctx, next) => {
    ctx.body = { code: 200, msg: '去往了用户管理' }
};
let goAboutUs_fn = async (ctx, next) => {
    ctx.render('aboutUs.html')
};


//查询所有用户
var goAdminUserControl_fn = async (ctx, next) => {
    //用户名
    var username = ctx.session.userName;

    //查找所有用户
    var allUsers = JSON.parse(JSON.stringify(await User.findAll({
        order: [
            ['id', 'ASC']
        ]
    })));

    //用户创建时间
    allUsers.forEach(QS => {
        if(QS.state==='1'){
            QS.states = '普通用户'
        }else if(QS.state==='2'){
            QS.states ='管理员'
        }else{
            QS.states ='陌生人'
        }
        QS.createTime = dateTime(JSON.parse(QS.createdAt));
    });

    var obj = {
        allUsers,
        username
    }
    ctx.render('adminUserControl.html', obj)
}

//修改管理员密码

//修改密码
let makeSure = async (ctx, next) => {
    var QSId = ctx.session.userId;
    
    let res = '';
    console.log(QSId);
    var password = ctx.request.body.password || '';
    var repassword = ctx.request.body.repassword || '';
    console.log(password);
    console.log(repassword);

    if (password.length > 0 && repassword.length > 0 && password === repassword) {
        var findUser = await User.findOne({
            where: {
                id: QSId
            }
        })
        let row = JSON.stringify(findUser);
        if (row.length > 0 && password === repassword) {
            var vim = await User.update({
                password: repassword
            }, {
                where: {
                    id: QSId
                }
            })
            let json1 = JSON.stringify(vim);
            console.log(json1); 
            if (json1 !== 'null') {
                res = { code: 200, msg: '修改密码成功' };


            } else {
                res = { code: 1000, msg: '修改密码失败' };

            }

        } else {
            res = { code: 1000, msg: '当前用户不存在' };

        }

    } else {
        res = { code: 1000, msg: '不能为空,输入的两次密码必须一致' };
    }
    console.log(res);

    ctx.body = JSON.stringify(res);

}

//管理员修改用户密码
/* 
let goAdminUpdate_fn=async(ctx,next)=>{

} */
let goAdminRevise_fn = async (ctx, next) => {
    ctx.render('adminRevise.html')
};

let goAdminQsResult_fn = async (ctx, next) => {

    var username = ctx.session.userName;
     // 查询所有问卷
     var allQS = JSON.parse(JSON.stringify(await newcreate.findAll({
        order: [
            ['id', 'ASC']
        ],
    })));

    // 用户表的所有数据
    var userAll = JSON.parse(JSON.stringify(await User.findAll()));

    // 用户回答答案卷的所有数据
    var userSQAll = JSON.parse(JSON.stringify(await score.findAll()));

    allQS.forEach(QS => {
        // console.log(QS);
        // console.log(QS.CreateTilte);
        // console.log(QS.publishUserId);

        // 该问卷发表的用户
        QS.publishUserName = userAll.filter(row => {
            return QS.CreaterUserId === row.id;
        })[0].username;
        // console.log(QS.publishUserName);

        // 参与该问卷发表的用户
        QS.userSQAll = userSQAll.filter(row => {
            return QS.id === row.qsId;
        }).length;
        // console.log(QS.userSQAll);

        // 问卷创建时间
        QS.screateTime = dateTime(JSON.parse(QS.createdAt));
    })
;

    var obj = {
        allQS,
        username
    }
    ctx.render('adminQsResult.html', obj)
}

//问卷结果表
let goAdminResult_fn = async (ctx,next)=>{ 
    //问卷Id
    var qsid = ctx.query.id;
    // console.log(qsid);

    // var username=ctx.session,username;
    // // 用户表的所有数据
    var userAll = JSON.parse(JSON.stringify(await User.findAll()));
    // console.log(userAll);

    // // 评分表所有数据
    var userSQAll = JSON.parse(JSON.stringify(await score.findAll({
        where:{
            qsId : qsid
        }
    })));
    console.log(userSQAll);

    userSQAll.forEach(user =>{
        // console.log(user.scoreId);
        user.username = userAll.filter(item=>{
            return user.scoreId  === item.id
        })[0].username;
        // console.log(user.username);
        user.SQSum = parseInt(user.scoreOne) + parseInt(user.scoreTwo) + parseInt(user.scoreThree) + parseInt(user.scoreFour) + parseInt(user.scoreFive) + parseInt(user.scoreSix) + parseInt(user.scoreSeven) + parseInt(user.scoreEight) + parseInt(user.scoreNine) + parseInt(user.scoreTen);
        // 计算平均分
        user.SQAvg = (parseInt(user.scoreOne) + parseInt(user.scoreTwo) + parseInt(user.scoreThree) + parseInt(user.scoreFour) + parseInt(user.scoreFive) + parseInt(user.scoreSix) + parseInt(user.scoreSeven) + parseInt(user.scoreEight) + parseInt(user.scoreNine) + parseInt(user.scoreTen)) / 10;

    })
    

     // 查询所有问卷
    var allQS = JSON.parse(JSON.stringify(await newcreate.findOne({
        where:{
            id : qsid
        }
    }))).CreateTilte;
    // console.log(allQS);

    // allQS.forEach(QS=>{
    //     //评分用户
    //     QS.publishUserName = userAll.filter(row => {
    //         return QS.scoreId === row.id;
    //     })[0].username;

        //
    // })
   
    let obj=
    {
        qsid,
        allQS,
        userSQAll
        // username,
        // allQS
    }
    ctx.render('adminResult.html',obj)
}
module.exports = {
    '/adminHome': ['post', auth, adminHome_fn],
    '/admin': ['get', auth, goAdminHome_fn],

    '/adminCreate': ['post', auth, adminCreate_fn],
    '/goAdminCreate': ['get', auth, goadminCreate_fn],
/* 
    '/adminQsMan': ['post', auth, adminQsMan_fn],
    '/index/goAdminQsMan': ['get', auth, goadminQsMan_fn], */

    '/adminQsResult': ['post', auth, adminQsResult_fn],
    '/index/goadminQsResult': ['get', auth, goAdminQsResult_fn],

    '/adminUserControl': ['post', auth, adminUserControl_fn],
    '/index/goAdminUserControl': ['get', auth, goAdminUserControl_fn],
    '/index/goAboutUs': ['get', auth, goAboutUs_fn],
    '/index/goAdminCreateSuccess': ['get', auth, goAdminCreateSuccess_fn],

    '/index/goAdminRevise': ['get', auth, goAdminRevise_fn],
    
    '/goAdminResult': ['get', auth, goAdminResult_fn],

    '/vimPwd': ["post", makeSure],
}
